package sakila.dal.film.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sakila.commonprocess.ProcessResult;
import sakila.dal.IDataAcess;
import sakila.dal.commondao.DataAccessHelper;
import sakila.dal.film.table.language;
import sakila.dto.film.BaseDTO;
import sakila.dto.film.LanguageDTO;
import sakila.sakilaexcetion.SakilaException;

public class LanguageDAO implements IDataAcess
{

	public ProcessResult delete() throws SakilaException
	{
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<LanguageDTO> getAll() throws SakilaException
	{
		List<LanguageDTO> result = new ArrayList<LanguageDTO>();

		String queryStr = "SELECT * FROM " + language.TABLE_NAME;

		ResultSet rs = DataAccessHelper.executeQueryNonParameters(queryStr);

		LanguageDTO languageDto;
		try
		{
			while (rs.next())
			{
				int id = rs.getInt(language.language_id);

				String name = rs.getString(language.name);
				Date lastUpdate = rs.getDate(language.last_update);

				languageDto = new LanguageDTO(id, name, lastUpdate);
				result.add(languageDto);
			}
			rs.close();
		}
		catch (SQLException e)
		{
			SakilaException.handleException("Fails to get all languages", e);
		}
		finally
		{
			DataAccessHelper.closeConnection();
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public LanguageDTO getById(int id) throws SakilaException
	{
		String queryStr = "SELECT * FROM " + language.TABLE_NAME + " WHERE " + language.language_id
		        + " = ?";
		ResultSet rs = DataAccessHelper.executeQueryWithParameters(queryStr, new Object[] { id });

		LanguageDTO languageDto = null;
		try
		{
			while (rs.next())
			{
				String name = rs.getString(language.name);
				Date lastUpdate = rs.getDate(language.last_update);

				languageDto = new LanguageDTO(id, name, lastUpdate);
			}
			rs.close();
		}
		catch (SQLException e)
		{
			SakilaException.handleException("Fails to get a languagesby id " + id, e);
		}
		finally
		{
			DataAccessHelper.closeConnection();
		}

		if (languageDto == null)
		{
			String errMsg = "Cannot get langague by id " + id;
			SakilaException.handleException(errMsg, new Exception(errMsg));
		}
		return languageDto;
	}

	public ProcessResult insert(BaseDTO newRecord) throws SakilaException
	{
		// TODO Auto-generated method stub
		return null;
	}

	public ProcessResult update(BaseDTO record) throws SakilaException
	{
		// TODO Auto-generated method stub
		return null;
	}

}
